package com.kingdee.eas.custom.tiog.bizbill.client;

import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.ctrl.kdf.table.ICell;
import com.kingdee.bos.ctrl.kdf.table.IRow;
import com.kingdee.bos.ctrl.kdf.table.KDTable;
import com.kingdee.bos.ctrl.kdf.table.event.KDTEditEvent;
import com.kingdee.bos.ctrl.kdf.table.event.KDTSelectEvent;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.ui.face.IUIFactory;
import com.kingdee.bos.ui.face.IUIWindow;
import com.kingdee.bos.ui.face.UIException;
import com.kingdee.bos.ui.face.UIFactory;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.common.client.OprtState;
import com.kingdee.eas.custom.tiog.basedata.CatalogMainInfo;
import com.kingdee.eas.custom.tiog.basedata.MeetingTypeInfo;
import com.kingdee.eas.custom.tiog.bizbill.CategoryListEntryDEntryInfo;
import com.kingdee.eas.custom.tiog.bizbill.CategoryListEntryInfo;
import com.kingdee.eas.custom.tiog.bizbill.SubjectCatalogEntryCollection;
import com.kingdee.eas.custom.tiog.bizbill.SubjectCatalogEntryInfo;
import com.kingdee.eas.custom.tiog.bizbill.SubjectFactory;
import com.kingdee.eas.custom.tiog.bizbill.SubjectInfo;
import com.kingdee.eas.custom.tiog.bizbill.util.CommonUtil;
import com.kingdee.eas.fm.cl.BillState;
import com.kingdee.eas.framework.client.ListUI;
import com.kingdee.eas.util.SysUtil;
import com.kingdee.eas.util.client.KDTableUtil;
import com.kingdee.eas.util.client.MsgBox;

/**
 * 
 * @description
 * @title CategoryListEditUICTEx 
 * @copyright 天津金蝶软件有限公司 
 * @author Strong Li Email:strong_li@kingdee.com
 * @date 2020-3-25
 */
public class CategoryListEditUICTEx extends CategoryListEditUI{
    
    public Map<String, List<CategoryListEntryDEntryInfo>> selected4GenD;
    public Map<String, CategoryListEntryInfo> selected4Gen;
    public String curSelectedEntry;

	public CategoryListEditUICTEx() throws Exception {
		super();
		selected4GenD = new HashMap<String, List<CategoryListEntryDEntryInfo>>();
		selected4Gen = new HashMap<String, CategoryListEntryInfo>();
		curSelectedEntry = "";
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public void actionEdit_actionPerformed(ActionEvent e) throws Exception {
	    // TODO Auto-generated method stub
	    super.actionEdit_actionPerformed(e);
            kdtEntrys.getColumn("isSelected").getStyleAttributes().setHided(true);
            kdtDEntrys.getColumn("isSelected").getStyleAttributes().setHided(true);
	    
	}
	
	@Override
	public void actionAudit_actionPerformed(ActionEvent e) throws Exception {
	    // TODO Auto-generated method stub
	    super.actionAudit_actionPerformed(e);
	}
	
	
	
	/**
	 * 
	 * @description
	 * @title onLoad
	 * @throws Exception
	 * @see com.kingdee.eas.framework.client.CoreBillEditUI#onLoad()
	 */
	@Override
	public void onLoad() throws Exception {
	    // TODO Auto-generated method stub
	    super.onLoad();
	    getOprtState();
	    if(isSelectState()){
	        this.genSubject.setEnabled(true);
	        int countEntry = this.kdtEntrys.getRowCount();
	        kdtEntrys.getColumn("isSelected").getStyleAttributes().setLocked(false);
	        kdtEntrys.setEditable(true);
    		kdtEntrys.getColumn("catalogMain").getStyleAttributes().setLocked(true);
    		kdtEntrys.getColumn("catalogMain").getStyleAttributes().setLocked(true);
    		if(countEntry > 0){
    		    for(int i = 0; i < countEntry; i++){
    		        IRow iRow = kdtEntrys.getRow(i);
    		        ICell iCell = iRow.getCell("isSelected");
    		        iCell.getStyleAttributes().setLocked(false);
    		        iCell.setValue(Boolean.FALSE);
    		    }
    		}
    		/**
    		 * 二级分录 会议安排
    		 */
    		int countDEntry = this.kdtDEntrys.getRowCount();
    		kdtDEntrys.getColumn("isSelected").getStyleAttributes().setLocked(false);
    		kdtDEntrys.setEditable(true);
                kdtDEntrys.getColumn("meetingType").getStyleAttributes().setLocked(true);
                kdtDEntrys.getColumn("meetingDes").getStyleAttributes().setLocked(true);
                if(countDEntry > 0){
                    for(int i = 0; i < countDEntry; i++){
                        IRow iRow = kdtDEntrys.getRow(i);
                        ICell iCell = iRow.getCell("isSelected");
                        
                        iCell.getStyleAttributes().setLocked(false);
                        iCell.setValue(Boolean.FALSE);
                    }
                }
	    } else {
	        kdtEntrys.getColumn("isSelected").getStyleAttributes().setHided(true);
	        kdtDEntrys.getColumn("isSelected").getStyleAttributes().setHided(true);
	    }
		
	}
	
	@Override
	public void actionGenSubject_actionPerformed(ActionEvent e)
			throws Exception {
	    // TODO Auto-generated method stub
	    super.actionGenSubject_actionPerformed(e);
	    //01获取选中列表
	    List<String> selectedIDs = getSelectedIDs();
	    //02根据selectedIDs生成
	    Map<String, CategoryListEntryInfo> entry = getEntryMap(selectedIDs);
	    //03校验selected4Gen里的数据合法性（不存在多会议类型）
	    MeetingTypeInfo meetingTypeInfo = isIlgelinvalidEntryDEntry();
	    //04
	    if(null == meetingTypeInfo || null == meetingTypeInfo.getId()){
                MsgBox.showError(this, "存在不同会议类型的事项，不允许生成议题！");
                SysUtil.abort();
	    }
            //05
	    IObjectPK iObjectPK = genSubject(meetingTypeInfo);
            //05
	    if(null != iObjectPK){
	        openSubjectWin(iObjectPK);
	    }
            //05
		
	}
	
	private void openSubjectWin(IObjectPK objectPK) throws UIException {
            // TODO Auto-generated method stub
            HashMap uiCtx = new HashMap();
            uiCtx.put("Owner", this);
            //uiCtx.put("canResize", this);
            uiCtx.put("ID", objectPK.toString());
            //com.kingdee.eas.base.uiframe.client.UINewFrameFactory
            //com.kingdee.eas.base.uiframe.client.UIModelDialogFactory
            IUIFactory uiFactory = UIFactory.createUIFactory("com.kingdee.eas.base.uiframe.client.UINewFrameFactory");
            IUIWindow tempVouUpdateDlg = uiFactory.create("com.kingdee.eas.custom.tiog.bizbill.client.SubjectEditUI", uiCtx, null, OprtState.EDIT);
            tempVouUpdateDlg.show();
        
        }

        private IObjectPK genSubject(MeetingTypeInfo meetingTypeInfo) throws EASBizException, BOSException {
            // TODO Auto-generated method stub
            SubjectInfo subjectInfo = new SubjectInfo();
            subjectInfo.setMeetingType(meetingTypeInfo);
            subjectInfo.setCompany(this.editData.getCompany());
            subjectInfo.setCompanyNumber(this.editData.getCompanyNumber());
            if(selected4Gen.size() > 0){
                SubjectCatalogEntryCollection subjectCatalogEntryColl = subjectInfo.getCatalogEntry();
                for(Entry<String, CategoryListEntryInfo> mapEntry : selected4Gen.entrySet()){
                    SubjectCatalogEntryInfo subjectCatalogEntryInfo = new SubjectCatalogEntryInfo();
                    CategoryListEntryInfo categoryListEntryInfo = mapEntry.getValue();
                    subjectCatalogEntryInfo.setCatalogMain(categoryListEntryInfo.getCatalogMain());
                    subjectCatalogEntryInfo.setCatalogMainNumber(categoryListEntryInfo.getCatalogNumber());
                    subjectCatalogEntryColl.add(subjectCatalogEntryInfo);
                }
            }
            IObjectPK pk = SubjectFactory.getRemoteInstance().addnew(subjectInfo);
            return pk;
        }
        
        /**
         * 
         * @description 验证会议类型是否一致
         * @title isIlgelinvalidEntryDEntry
         * @return
         * @author Strong Li
         */
        private MeetingTypeInfo isIlgelinvalidEntryDEntry() {
            // TODO Auto-generated method stub
            String first = "";
            MeetingTypeInfo meetingTypeInfo = new MeetingTypeInfo();
            for(Entry<String, List<CategoryListEntryDEntryInfo>> map : selected4GenD.entrySet()){
                List<CategoryListEntryDEntryInfo> list = map.getValue();
                for(CategoryListEntryDEntryInfo categoryListEntryDEntryInfo : list){
                    if("".equals(first)){
                        //第一次被调用
                        first = categoryListEntryDEntryInfo.getMeetingType().getId().toString();
                        meetingTypeInfo = categoryListEntryDEntryInfo.getMeetingType();
                    } else if(!"".equals(first) && first.equals(categoryListEntryDEntryInfo.getMeetingType().getId().toString())){
                        first = categoryListEntryDEntryInfo.getMeetingType().getId().toString();
                    } else {
                        //有不同的会议类型
                        return null;
                    }
                }
            }
            return meetingTypeInfo;
        }

        private Map<String, CategoryListEntryInfo> getEntryMap(List<String> selectedIDs) {
            // TODO Auto-generated method stub
            Map<String, CategoryListEntryInfo> entry = new HashMap<String, CategoryListEntryInfo>();
            int countEntry = this.kdtEntrys.getRowCount();
            kdtEntrys.getColumn("isSelected").getStyleAttributes().setLocked(false);
            kdtEntrys.setEditable(true);
            kdtEntrys.getColumn("catalogMain").getStyleAttributes().setLocked(true);
            kdtEntrys.getColumn("catalogMain").getStyleAttributes().setLocked(true);
            if(countEntry > 0){
                    for(int i = 0; i < countEntry; i++){
                            IRow iRow = kdtEntrys.getRow(i);
                            ICell iCell = iRow.getCell("isSelected");
                            
                            iCell.getStyleAttributes().setLocked(false);
                            iCell.setValue(Boolean.FALSE);
                    }
            }
            return entry;
        }

        @Override
	public void kdtEntrys_Changed(int rowIndex, int colIndex) throws Exception {
            // TODO Auto-generated method stub
            super.kdtEntrys_Changed(rowIndex, colIndex);
            if(isSelectState()){
                IRow iRow = kdtEntrys.getRow(rowIndex);
                Boolean isSelected = (Boolean) iRow.getCell("isSelected").getValue();
                String entryId_Key = iRow.getCell("id").getValue().toString();
                if(isSelected){
                    //刚又被 nothing todo记录当前被选中的分录数据行
                    curSelectedEntry = entryId_Key;
                    addMapEntry(entryId_Key, iRow);
                } else {
                    //清空
                    cleanTableSelectedState(kdtDEntrys);
                    //清除被选中的一级分录
                    removeMapEntry(entryId_Key);
                    //清除被选中的二级分录
                    removeMapDEntry(entryId_Key);
                }
                
            }
        	    
	}
	
	private void removeMapDEntry(String entryId_Key) {
            // TODO Auto-generated method stub
	    if(selected4GenD.containsKey(entryId_Key))
	        selected4GenD.remove(entryId_Key);
	    
        }

        private void removeMapEntry(String entryId_Key) {
            // TODO Auto-generated method stub
            if(selected4Gen.containsKey(entryId_Key)){
                selected4Gen.remove(entryId_Key);
            }
        }

        private void addMapEntry(String entryId_Key, IRow row) {
            // TODO Auto-generated method stub
	    CategoryListEntryInfo categoryListEntryInfo = new CategoryListEntryInfo();
	    categoryListEntryInfo.setCatalogMain((CatalogMainInfo) row.getCell("catalogMain").getValue());
	    //无论如何要更新最新categoryListEntryInfo
	    if(selected4Gen.containsKey(entryId_Key)){
	        selected4Gen.put(entryId_Key, categoryListEntryInfo);
	    }else{
	        selected4Gen.put(entryId_Key, categoryListEntryInfo);
	    }
        }

        private void cleanTableSelectedState(KDTable kdtDEntrys) {
        // TODO Auto-generated method stub
        
            int countDEntry = this.kdtDEntrys.getRowCount();
            kdtDEntrys.getColumn("isSelected").getStyleAttributes().setLocked(false);
            kdtDEntrys.setEditable(true);
            kdtDEntrys.getColumn("meetingType").getStyleAttributes().setLocked(true);
            kdtDEntrys.getColumn("meetingDes").getStyleAttributes().setLocked(true);
            if(countDEntry > 0){
                    for(int i = 0; i < countDEntry; i++){
                            IRow iRow = kdtDEntrys.getRow(i);
                            ICell iCell = iRow.getCell("isSelected");
                            
                            iCell.getStyleAttributes().setLocked(false);
                            iCell.setValue(Boolean.FALSE);
                    }
            }
        }

	@Override
	protected void kdtEntrys_tableSelectChanged(KDTSelectEvent e) throws Exception {
    	    // TODO Auto-generated method stub
    	    super.kdtEntrys_tableSelectChanged(e);
    	    if(isSelectState()){
                int countDEntry = this.kdtDEntrys.getRowCount();
                kdtDEntrys.getColumn("isSelected").getStyleAttributes().setLocked(false);
                kdtDEntrys.setEditable(true);
                kdtDEntrys.getColumn("meetingType").getStyleAttributes().setLocked(true);
                kdtDEntrys.getColumn("meetingDes").getStyleAttributes().setLocked(true);
                if(countDEntry > 0){
                    for(int i = 0; i < countDEntry; i++){
                        IRow iRow = kdtDEntrys.getRow(i);
                        //先将单选框置成未勾选状态，后期再改
                        ICell iCell = iRow.getCell("isSelected");
                        iCell.setValue(Boolean.FALSE);
                        //获取当前二级分录行的id
                        iCell = iRow.getCell("id");
                        String curID = iCell.getValue().toString();
                        if(selected4GenD.size() > 0){
                            //遍历Map
                            for(Entry<String, List<CategoryListEntryDEntryInfo>> map : selected4GenD.entrySet()){
                                List<CategoryListEntryDEntryInfo> list = map.getValue();
                                if(list.size() > 0){
                                    //遍历List
                                    for(CategoryListEntryDEntryInfo info : list){
                                        String loopID = info.getId().toString();
                                        if(loopID.equals(curID)){
                                            iCell = iRow.getCell("isSelected");
                                            iCell.setValue(Boolean.TRUE);
                                        }
                                    }
                                }
                            }
                        }//
                    }
                }
    	        
    	    }
	}
	
	/**
	 * 
	 * @description 二级分录选择变化
	 * @title kdtDEntrys_Changed
	 * @param rowIndex
	 * @param colIndex
	 * @throws Exception
	 * @see com.kingdee.eas.custom.tiog.bizbill.client.AbstractCategoryListEditUI#kdtDEntrys_Changed(int, int)
	 */
	@Override
	public void kdtDEntrys_Changed(int rowIndex, int colIndex) throws Exception {
            // TODO Auto-generated method stub
            super.kdtDEntrys_Changed(rowIndex, colIndex);
            if(isSelectState()){
                IRow iRow = kdtDEntrys.getRow(rowIndex);
                Boolean isSelected = (Boolean) iRow.getCell("isSelected").getValue();
                iRow.getCell("id").getValue().toString();
                
                CategoryListEntryDEntryInfo categoryListEntryDEntryInfo = new CategoryListEntryDEntryInfo();
                categoryListEntryDEntryInfo.setId((BOSUuid) iRow.getCell("id").getValue());
                categoryListEntryDEntryInfo.setMeetingType((MeetingTypeInfo) iRow.getCell("meetingType").getValue());
                
                if(isSelected){
                    //刚又被 nothing todo
                    if(selected4GenD.containsKey(curSelectedEntry)){
                        undoRepeatAddMap(curSelectedEntry, categoryListEntryDEntryInfo);
                    } else {
                        addMap(curSelectedEntry, categoryListEntryDEntryInfo);
                    }
                } else {
                    //除去
                    removeMap(curSelectedEntry, categoryListEntryDEntryInfo);
                }
                
            }
	}
	
	/**
	 * 
	 * @description 判断单据是否需要出现选择框
	 * @title isSelectState
	 * @return
	 * @author Strong Li
	 */
	private boolean isSelectState() {
            // TODO Auto-generated method stub
	    if(!"EDIT".equals(getOprtState()) && editData.getState().equals(com.kingdee.eas.custom.tiog.bizbill.BillState.Audited))
	        return true;
            return false;
        }

        /**
	 * 
	 * @description 二级分录 反选后删除元素
	 * @title removeMap
	 * @param curSelectedEntry
	 * @param categoryListEntryDEntryInfo
	 * @author Strong Li
	 */
	private void removeMap(String curSelectedEntry, CategoryListEntryDEntryInfo categoryListEntryDEntryInfo) {
            // TODO Auto-generated method stub
            List<CategoryListEntryDEntryInfo> sategoryListEntryDEntryInfos = selected4GenD.get(curSelectedEntry);
            if(sategoryListEntryDEntryInfos.size() > 0){
                for(CategoryListEntryDEntryInfo categoryListEntryDEntryInfoTemp : sategoryListEntryDEntryInfos){
                    if(categoryListEntryDEntryInfoTemp.getId().toString().equals(categoryListEntryDEntryInfo.getId().toString())){
                        sategoryListEntryDEntryInfos.remove(categoryListEntryDEntryInfoTemp);
                        break;
                    }
                }
            }
        
        }

        /**
	 * 
	 * @description 二级分录直接新增元素
	 * @title addMap
	 * @param curSelectedEntry
	 * @param categoryListEntryDEntryInfo
	 * @author Strong Li
	 */
	private void addMap(String curSelectedEntry, CategoryListEntryDEntryInfo categoryListEntryDEntryInfo) {
            // TODO Auto-generated method stub
	    List<CategoryListEntryDEntryInfo> sategoryListEntryDEntryInfos = new ArrayList<CategoryListEntryDEntryInfo>();
	    sategoryListEntryDEntryInfos.add(categoryListEntryDEntryInfo);
	    selected4GenD.put(curSelectedEntry, sategoryListEntryDEntryInfos);
        }

	/**
	 * 
	 * @description 二级分录去重新增元素
	 * @title undoRepeatAddMap
	 * @param curSelectedEntry
	 * @param categoryListEntryDEntryInfo
	 * @author Strong Li
	 */
        private void undoRepeatAddMap(String curSelectedEntry,
                CategoryListEntryDEntryInfo categoryListEntryDEntryInfo) {
            // TODO Auto-generated method stub
            boolean exist = false;
            List<CategoryListEntryDEntryInfo> sategoryListEntryDEntryInfos = selected4GenD.get(curSelectedEntry);
            if(sategoryListEntryDEntryInfos.size() > 0){
                for(CategoryListEntryDEntryInfo categoryListEntryDEntryInfoTemp : sategoryListEntryDEntryInfos){
                    if(categoryListEntryDEntryInfoTemp.getId().toString().equals(categoryListEntryDEntryInfo.getId().toString())){
                        break;
                    }
                }
                if(!exist)
                    sategoryListEntryDEntryInfos.add(categoryListEntryDEntryInfo);
            }
        }


        @Override
	protected void kdtDEntrys_editValueChanged(KDTEditEvent e) throws Exception {
            // TODO Auto-generated method stub
            super.kdtDEntrys_editValueChanged(e);
	}
	

	private List<String> getSelectedIDs() {
	    // TODO Auto-generated method stub
	    List selectedIDs = new ArrayList();
		
	    int[] selectIds = KDTableUtil.getSelectedRows(this.kdtEntrys);
	    boolean hasSelectedIDs = false;
	    for(int i = 0; i < kdtEntrys.getRowCount(); i++){
	        IRow iRow = kdtEntrys.getRow(i);
	        ICell iCell = iRow.getCell("isSelected");
                Boolean isSelected = (Boolean) iCell.getValue();
                if(isSelected){
                    hasSelectedIDs = true;
                    String id = kdtEntrys.getRow(i).getCell("id").getValue().toString();
                    if (null != id && !"".equals(id))
                            selectedIDs.add(id);
                }
	    }
		
	    if (!hasSelectedIDs) {
	        MsgBox.showError(this, "请选择单据！");
	        SysUtil.abort();
	    }

	    return selectedIDs;
	}


}
